package com.example.interview.feizhu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 按顺序打印ABC十次
 */
public class timu2 {
    static volatile int state = 1;
    static final ReentrantLock lock = new ReentrantLock();
    static final Condition first = lock.newCondition();
    static final Condition second = lock.newCondition();
    static final Condition third = lock.newCondition();

    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    lock.lock();
                    while (state != 1) {
                        try {
                            first.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("A");
                    state = 2;
                    second.signal();
                    lock.unlock();
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    lock.lock();
                    while (state != 2) {
                        try {
                            second.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print("B");
                    state = 3;
                    third.signal();
                    lock.unlock();
                }
            }
        });

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    lock.lock();
                    while (state != 3) {
                        try {
                            third.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("C");
                    state = 1;
                    first.signal();
                    lock.unlock();
                }
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();

    }
}
